from playwright.sync_api import sync_playwright
import os
import pickle
import markdown
import time
from dotenv import load_dotenv
load_dotenv()
from tech_article_service import TechArticleService
import random


# 1. 登录并保存会话
def save_session():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)  # 可设为 True 进行无头运行
        context = browser.new_context()

        # 1. 打开登录页
        page = context.new_page()
        page.goto("https://jishuba.cn/wp-login.php")  # 换成你自己的后台登录地址

        # 2. 登录
        page.fill('input[name="log"]', "jsb")
        page.fill('input[name="pwd"]', "bsj@WSX")
        page.click('input[name="wp-submit"]')

        # 等待跳转到后台页面
        page.wait_for_url("**/wp-admin/")

        # 3. 保存 cookies 和 localStorage
        cookies = context.cookies()
        with open("session_cookies.pkl", "wb") as f:
            pickle.dump(cookies, f)

        print("✅ 会话已保存，成功登录！")
        browser.close()


def publish_article(title: str, content: str):
    with sync_playwright() as p:
        # browser = p.chromium.launch(headless=False)  # 可设为True进行无头运行
        # context = browser.new_context()
        user_data_dir = '/Users/martinzhang/Library/Application Support/Google/Chrome_playwright'
        if not os.path.exists(user_data_dir):
            os.makedirs(user_data_dir)

        context = p.chromium.launch_persistent_context(
            # executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
            user_data_dir=user_data_dir,
            headless=False,
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
        )
        
        # 1. 加载之前保存的 cookies（如果文件存在）
        # if os.path.exists("session_cookies.pkl"):
        #     with open("session_cookies.pkl", "rb") as f:
        #         cookies = pickle.load(f)
        #         context.add_cookies(cookies)
        #     print("✅ 已加载会话，无需重新登录！")
        # else:
        #     print("❌ 找不到会话文件，开始登录...")
        #     save_session()  # 如果没有会话，执行登录保存会话
        #     return  # 登录后保存会话就退出
        
        page = context.new_page()
        
        page.goto("https://jishuba.cn/wp-admin/post-new.php") 
        
        page.mouse.move(200, 150, steps=10) 
        
        page.evaluate(f"""
                async () => {{
                    await navigator.clipboard.write([
                        new ClipboardItem({{
                            "text/html": new Blob([`{title}`], {{ type: "text/html" }}),
                            "text/plain": new Blob([`{title}`], {{ type: "text/plain" }})
                        }})
                    ]);
                }}
                """)
        
        # page.locator('text="添加标题"').click()  
        
        page.keyboard.press('Meta+V')  
        # content_area = page.locator('p.block-editor-default-block-appender__content')
        # content_area = page.locator('text=输入 / 来选择一个区块')
        # content_area.click()
        # page.evaluate('document.querySelector("p.block-editor-default-block-appender__content").click()')
        page.mouse.move(316, 684, steps=10)
        random_wait(page)
        page.mouse.click()
        html_content = content 
        # 将 HTML 放入剪贴板，并声明为 HTML 类型
        page.evaluate(f"""
                async () => {{
                    await navigator.clipboard.write([
                        new ClipboardItem({{
                            "text/html": new Blob([`{html_content}`], {{ type: "text/html" }}),
                            "text/plain": new Blob([`{html_content}`], {{ type: "text/plain" }})
                        }})
                    ]);
                }}
                """)
        # iframe = page.frame_locator("iframe[name='editor-canvas']")
        # iframe.locator("div.block-editor-rich-text__editable").click()
        page.keyboard.press('Meta+V') 
        # editor = page.locator('div.block-editor-rich-text__editable')
        # editor.click()
        # page.keyboard.insert_text(content)
        # content = repr(content)
        # script_text = f"""element => {{
        #             element.focus();
        #             element.innerHTML = `{content}`;
        #             element.dispatchEvent(new Event('input', {{ bubbles: true }}));
        #         }}"""
        # page.eval_on_selector(
        #         "p.block-editor-rich-text__editable",
        #         script_text
        #         )
        # time.sleep(2)
        # 5. 点击发布按钮
        page.click('button.editor-post-save-draft')  # 你需要根据你网站按钮的实际 id/class 修改

        # 6. 确认发布完成（比如等待跳转或显示“发布成功”）
        page.wait_for_selector("button.editor-post-save-draft")

        print("✅ 文章已成功发布！")

        # time.sleep(2)
        # browser.close()
def random_wait(page):
    wait_time = random.uniform(1, 5)  # 生成 1 到 5 秒之间的随机等待时间
    page.wait_for_timeout(wait_time * 1000)  # 将秒转换为毫秒
    
def get_and_publish_article():
    techarticleService = TechArticleService()
    articles = techarticleService.get_articles()
    # print(articles)
    for article in articles:
        cn_content = article['cn_content']
        title = cn_content['title']
        content = cn_content['content']
        content = markdown.markdown(content)
        content = content.replace('\n', '')
        publish_article(title, content)
        techarticleService.update_published(article['id'])
        print(f"✅ 文章《{title}》已成功发布！")


def test_publish_article():
    content_file_path = '/Users/martinzhang/mt-20230221/zxjd-proj-20240405/04-development/jishuba/note_mind/resources/article-q-02.md'
    content = ''
    with open(content_file_path, 'r') as f:
        content = f.read()
    article = {
        "title": "自动发布测试文章",
        "content": "这是使用 Playwright 自动发布的内容，内容正文部分支持格式、图片、链接等。"
    }
    title, content = TechArticleService.extract_title_and_content(content)
    content = markdown.markdown(content)
    content = content.replace('\n', '')
    
    publish_article(title, content)
    
if __name__ == "__main__":  
    get_and_publish_article()
    # test_publish_article()
    print("DONE")
    
